package com.neusoft.elmboot.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.elmboot.po.OrderDetailet;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @PostMapping
    public ResponseEntity<Integer> createOrders(@RequestParam String userId,
                                                @RequestParam Integer businessId,
                                                @RequestParam Double orderTotal,
                                                @RequestParam Integer daId,
                                                @RequestParam Integer orderState,
                                                @RequestParam String orderItemsJson) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<OrderDetailet> orderItems = objectMapper.readValue(orderItemsJson, new TypeReference<List<OrderDetailet>>() {});
            Orders order = new Orders();
            order.setUserId(userId);
            order.setBusinessId(businessId);
            order.setOrderTotal(orderTotal);
            order.setDaId(daId);
            order.setOrderState(orderState);
            int orderId = ordersService.createOrders(order, orderItems);
            return ResponseEntity.ok(orderId);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/{orderId}")
    public Orders getOrdersById(@PathVariable Integer orderId) throws Exception {
        return ordersService.getOrdersById(orderId);
    }

    @GetMapping("/list")
    public List<Orders> listOrdersByUserId(@RequestParam String userId) throws Exception {
        return ordersService.listOrdersByUserId(userId);
    }

    @PatchMapping("/state")
    public ResponseEntity<?> updateOrderState(@RequestBody Map<String, Object> payload) {
        // 原逻辑不动
        return null; // 省略
    }
}